package com.fendaren.controller;

import com.fendaren.pojo.UserAddress;
import com.fendaren.pojo.bo.AddressBO;
import com.fendaren.service.AddressService;
import com.fendaren.utils.JSONResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @PostMapping("/list")
    public JSONResult list(@RequestParam String userId) {

        if (StringUtils.isBlank(userId)) {
            return JSONResult.errorMsg("");
        }
        List<UserAddress> list = addressService.queryAll(userId);
        return JSONResult.ok(list);
    }

    @PostMapping("/add")
    public JSONResult add(@RequestBody AddressBO addressBO) {
        addressService.addNewUserAddress(addressBO);
        return JSONResult.ok();
    }

    @PostMapping("/update")
    public JSONResult update(@RequestBody AddressBO addressBO) {
        if (StringUtils.isBlank(addressBO.getAddressId())) {
            return JSONResult.errorMsg("修改地址错误：addressId不能为空");
        }

        addressService.updateUserAddress(addressBO);
        return JSONResult.ok();
    }

    @PostMapping("delete")
    public JSONResult delete(@RequestParam String userId, @RequestParam String addressId) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(addressId)) {
            return JSONResult.errorMsg("");
        }

        addressService.deleteUserAddress(userId, addressId);

        return JSONResult.ok();
    }

    @PostMapping("/setDefault")
    public JSONResult setDefault(@RequestParam String userId, @RequestParam String addressId) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(addressId)) {
            return JSONResult.errorMsg("");
        }
        addressService.updateUserAddressToBeDefault(userId, addressId);
        return JSONResult.ok();
    }
}
